# -*- coding: utf-8 -*-

from bopress.hook import add_submenu_page, add_action
from bopress.orm import SessionFactory, pk
from bopress.utils import Utils
from orm_demo.models import School, Student, StudentBaseInfo, Teacher

__author__ = 'yezang'


def data(handler):
    s = SessionFactory.session()
    # 对象关联创建,老师与学生都跟学校是多对一的关系，所以学校可以批量添加它们
    school = School()
    school.school_id = pk()
    school.name = Utils.random_str()
    school.teacher_set = [Teacher(teacher_id=pk(), name=Utils.random_str()),
                          Teacher(teacher_id=pk(), name=Utils.random_str())]
    school.student_set = [Student(student_id=pk(), name=Utils.random_str()),
                          Student(student_id=pk(), name=Utils.random_str())]
    s.add(school)
    s.commit()

    # 学校可以查询此学校下的所有学生与老师
    print('学校里的老师', school.teacher_set.all())
    print('学校里的学生', school.student_set.all())

    t1 = Teacher(teacher_id=pk(), name=Utils.random_str())
    s1 = Student(student_id=pk(), name=Utils.random_str())
    info = StudentBaseInfo(student_base_info_id=pk(), name=Utils.random_str())
    s1.studentbaseinfo = info
    school.teacher_set.append(t1)
    school.student_set.append(s1)

    s.commit()
    # 学生与学生基本信息一对一，互相可以访问对方的唯一实例
    print('学生基本信息', s1.studentbaseinfo)
    print('学生', info.student)
    # 老师与学生可以得到唯一的学校对象
    print('老师的学校', t1.school)
    print('学生的学校', s1.school)

    # 学生与老师多对多，任意一方都可以批量添加另外一方
    t1.student_set.append(s1)
    t1.student_set.append(Student(student_id=pk(), name=Utils.random_str(), school=school))
    t1.student_set.append(Student(student_id=pk(), name=Utils.random_str(), school=school))
    t1.student_set.append(Student(student_id=pk(), name=Utils.random_str(), school=school))
    t1.student_set.append(Student(student_id=pk(), name=Utils.random_str(), school=school))
    t1.student_set.append(Student(student_id=pk(), name=Utils.random_str(), school=school))

    s.commit()

    print('老师的学生集合', t1.student_set.all())
    print('学生的老师集合', s1.teacher_set.all())

    handler.render_json()


add_submenu_page("dev-example", "ORM 关系例子", "ORM 关系例子", "orm-example", ["r_read"], 'orm_demo/tpl/orm.html')
add_action('bo_api_post_orm_test', data)
